package com.smartcar.sms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.smartcar.common.domain.request.SendEmailVo;
import com.smartcar.sms.mapper.SmsLogMapper;
import com.smartcar.sms.mapper.SmsMapper;
import com.smartcar.sms.service.SmsService;
import com.sms.common.domain.SmsTemplates;
import com.sms.common.domain.SmsTemplatesLog;
import com.sms.common.domain.request.QuerySmsVo;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.text.StringSubstitutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @ClassName 小渣渣
 * @Description TODO
 * @date 2023/10/26 16:33
 * @Version 1.0
 */
@Service
@Log4j2
public class SmsServiceImpl implements SmsService {

    @Autowired
    private SmsMapper smsMapper;

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String username;

    @Autowired
    private SmsLogMapper smsLogMapper;

    @Override
    @GlobalTransactional(name = "selectSms")
    public PageInfo<SmsTemplates> querySms(QuerySmsVo querySmsVo) {
        log.info("=============用户查询=================");
        log.info("当前 XID: {}", RootContext.getXID());
        PageHelper.startPage(querySmsVo.getPageNum(), querySmsVo.getPageSize());
        // mybaits-plus
        /*List<SmsTemplates> list = smsMapper.selectList(new QueryWrapper<SmsTemplates>()
                .like("sms_title", querySmsVo.getSmsTitle()));*/
        // mybaits
        List<SmsTemplates> list = smsMapper.querySms(querySmsVo);
        PageInfo<SmsTemplates> info = new PageInfo<>(list);
        return info;
    }

    @Override
    @GlobalTransactional(name = "createSms")
    public int insertSms(SmsTemplates smsTemplates) {
        log.info("=============用户下单=================");
        log.info("当前 XID: {}", RootContext.getXID());
        // 添加创建时间
        Stream.of(smsTemplates).map(
                item -> {
                    item.setCreateTime(new Date());
                    return item;
                }
        ).collect(Collectors.toList());
        return smsMapper.insert(smsTemplates);
    }

    @Override
    @Transactional
    public int updateSmsById(SmsTemplates smsTemplates) {
        // 添加修改时间
        Stream.of(smsTemplates).map(
                item -> {
                    item.setUpdateTime(new Date());
                    return item;
                }
        ).collect(Collectors.toList());
        return smsMapper.updateById(smsTemplates);
    }

    @Override
    public void sendEmail(SendEmailVo sendEmailVo) {
        SimpleMailMessage message = new SimpleMailMessage();
        // 发件人 你的邮箱
        message.setFrom(username);
        // 接收人 接收者邮箱
        message.setTo(sendEmailVo.getEmail());
        // 查询短信模板
        SmsTemplates smsTemplates = smsMapper.selectOne(new QueryWrapper<SmsTemplates>()
                .eq("sms_type", sendEmailVo.getSmsType()));
        // 邮件标题
        message.setSubject(smsTemplates.getSmsTitle());
        // 检查邮件内容中是否含有变量
        // 编译正则表达式
        Pattern pattern = Pattern.compile(".*\\$\\{.*\\}.*");
        if (pattern.matcher(smsTemplates.getSmsText()).matches()) {
            //替换模板内变量
            StringSubstitutor stringSubstitutor = new StringSubstitutor(sendEmailVo.getSmsVariable());
            smsTemplates.setSmsText(stringSubstitutor.replace(smsTemplates.getSmsText()));
        }
        // 邮件内容
        message.setText(smsTemplates.getSmsText());
        // 发送邮件
        javaMailSender.send(message);
        // 记录邮件发送
        SmsTemplatesLog smsTemplatesLog = SmsTemplatesLog.builder()
                .smsText(smsTemplates.getSmsText()).build();
        insertSmsTemplatesLog(smsTemplatesLog);
    }

    @Override
    public void loginEmail(String nickName, String email) {
        String smsType = "loginEmail";
        HashMap<String, String> smsVariable = new HashMap<>();
        smsVariable.put("nickName", nickName);
        SendEmailVo sendEmailVo = new SendEmailVo();
        sendEmailVo.setEmail(email);
        sendEmailVo.setSmsType(smsType);
        sendEmailVo.setSmsVariable(smsVariable);
        // 发送邮件
        sendEmail(sendEmailVo);
    }

    public void insertSmsTemplatesLog(SmsTemplatesLog smsTemplatesLog) {
        smsLogMapper.insert(smsTemplatesLog);
    }
}
